on findLastTargetIndex(targetItem, itemList)
	set lastIndex to 0
	repeat with i from (count of itemList) to 1 by -1
		if item i of itemList is targetItem then
			set lastIndex to i
			exit repeat
		end if
	end repeat
	return lastIndex
end findLastTargetIndex
beep 1
say "开始执行随航"
beep 1

tell application "System Settings"
	activate
	delay 1
	tell application "System Events"
		tell process "System Settings"
			click menu item "显示器" of menu "显示" of menu bar item "显示" of menu bar 1
			delay 0.3
			tell group 1 of group 2 of splitter group 1 of group 1 of window "显示器"
				try
					-- 等待“添加”按钮出现
					set buttonFound to false
					set timeoutSeconds to 10 -- 设置超时时间（秒）
					set startTime to current date
					repeat
						try
							-- 尝试获取“添加”按钮
							set addButton to pop up button "添加"
							set buttonFound to true
							exit repeat
						on error
							-- 如果按钮未找到，检查是否超时
							if (current date) - startTime > timeoutSeconds then
								say "超时：未找到“添加”按钮"
								return
							end if
							delay 0.5 -- 等待 0.5 秒后重试
						end try
					end repeat
					
					-- 如果找到“添加”按钮，继续执行
					if buttonFound then
						click addButton
						-- 获取所有菜单项的名称
						set menuItems to name of menu items of menu "添加" of pop up button "添加"
						-- 通过名字查找要准确一些，这里去找最后一个名字的索引，因为如果符合通用控制的调节，就会出现两个名字，一个是通用控制，一个是随航
						set targetIndex to (my findLastTargetIndex("LiDongDongiPadPro", menuItems))
						-- 点击目标菜单项
						delay 0.3
						click menu item targetIndex of menu "添加" of pop up button "添加"
						say "操作成功，随航已连接或断开"
					end if
				on error
					delay 0.5
					say "未找到或发生错误: " & errorMessage
					exit
				end try
			end tell
		end tell
	end tell
end tell
delay 1
beep 1
--完成后退出设置
tell application "System Settings" to quit
